package com.jysz.certificate.service.system;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Subqueries;
import org.springframework.stereotype.Service;

import com.jysz.certificate.persistence.dao.system.RegionDao;
import com.jysz.certificate.persistence.enums.RegionEnum;
import com.jysz.certificate.persistence.model.system.Region;
import com.jysz.certificate.persistence.model.system.RegionDTO;
import com.jysz.certificate.utils.CommonUtil;
import com.jysz.webcore.ssh.orm.hibernate.support.Page;
import com.jysz.webcore.ssh.service.EntityService;

@Service
public class RegionService extends EntityService<Region, Long, RegionDao>{
	
	@Resource
	private RegionDao regionDao;
	
	@Override
	public RegionDao getEntityDao() {
		return regionDao;
	}
	
	//(列表)
	public Page<Region> findPage(RegionDTO search, int pageNo, int pageSize) {
		
		Criteria criteria = regionDao.createCriteria();
		if(search!=null&&CommonUtil.isNotEmpty(search.getName())){
			DetachedCriteria dc = DetachedCriteria.forClass(Region.class);
			dc.setProjection(Projections.property("id"));
			dc.add(Restrictions.like("name", search.getName(),MatchMode.ANYWHERE));
//			dc.setProjection(Projections.property("id"));
//			criteria.add(Subqueries.in("id", dc));
			criteria.add(Restrictions.or(Restrictions.like("name", search.getName(), MatchMode.ANYWHERE), Subqueries.propertyIn("parent", dc)));
			
		}
		if(search!=null&&search.getType()!=null&&search.getType()>0){
			criteria.add(Restrictions.eq("type", RegionEnum.index(search.getType())));
		}else{
			criteria.add(Restrictions.or(Restrictions.eq("type", RegionEnum.PROVINCE), Restrictions.eq("type", RegionEnum.CITY)));
		}
		criteria.addOrder(Order.asc("parent"));
		return this.findPage(criteria, pageNo, pageSize);
	}
	
	public List<Region> index(){
		Criteria c=regionDao.createCriteria();
		c.add(Restrictions.eq("type", RegionEnum.PROVINCE));
		
		return c.list();
	}
	
	public List<Region> findByType(RegionEnum type){
		
		Criteria c=regionDao.createCriteria();
		c.add(Restrictions.eq("type", type));
		return c.list();
	}
	
	public Region findByName(String name){
		
		Criteria c=regionDao.createCriteria();
		c.add(Restrictions.eq("name", name));
		List<Region> list=c.list();
		if(list!=null&&list.size()>0)
			return list.get(0);
		return null;
	}
}
